import { ElMessage, ElMessageBox } from 'element-plus'
import { feeDuplicateCheckApi, FeeDuplicateCheckResult } from '@/api/property'

/**
 * 费用重复检查工具函数
 * 
 * @author Wu.Liang
 * @since 2025-01-30
 * @version 1.0.0
 */

/**
 * 检查物业费重复
 * @param communityId 社区ID
 * @param billingPeriod 计费周期
 * @param feeType 费用类型
 * @returns Promise<boolean> true-无重复，false-有重复
 */
export const checkPropertyFeeDuplicate = async (
  communityId: number,
  billingPeriod: string,
  feeType: number
): Promise<boolean> => {
  try {
    const response = await feeDuplicateCheckApi.checkPropertyFeeDuplicate({
      communityId,
      billingPeriod,
      feeType
    })

    if (response.code === 200) {
      const result = response.data as FeeDuplicateCheckResult
      
      if (result.hasDuplicate) {
        // 显示重复记录详情
        await showDuplicateDetails(result, '物业费')
        return false
      } else {
        return true
      }
    } else {
      ElMessage.error(response.data.message || '检查失败')
      return false
    }
  } catch (error) {
    console.error('检查物业费重复失败:', error)
    ElMessage.error('检查失败，请重试')
    return false
  }
}

/**
 * 检查卫生费重复
 * @param communityId 社区ID
 * @param billingPeriod 计费周期
 * @returns Promise<boolean> true-无重复，false-有重复
 */
export const checkSanitationFeeDuplicate = async (
  communityId: number,
  billingPeriod: string
): Promise<boolean> => {
  try {
    const response = await feeDuplicateCheckApi.checkSanitationFeeDuplicate({
      communityId,
      billingPeriod
    })

    if (response.code === 200) {
      const result = response.data as FeeDuplicateCheckResult
      
      if (result.hasDuplicate) {
        // 显示重复记录详情
        await showDuplicateDetails(result, '卫生费')
        return false
      } else {
        return true
      }
    } else {
      ElMessage.error(response.data.message || '检查失败')
      return false
    }
  } catch (error) {
    console.error('检查卫生费重复失败:', error)
    ElMessage.error('检查失败，请重试')
    return false
  }
}

/**
 * 显示重复记录详情
 * @param result 重复检查结果
 * @param feeTypeName 费用类型名称
 */
const showDuplicateDetails = async (result: FeeDuplicateCheckResult, feeTypeName: string) => {
  let message = `发现${feeTypeName}重复记录：\n\n`
  
  if (result.checkType === 'community') {
    message += `社区级别重复：已存在计费周期为 "${result.duplicateRecords?.[0]?.billingPeriod}" 的记录\n`
    message += `重复数量：${result.duplicateCount} 条\n\n`
  } else if (result.checkType === 'household') {
    message += `房户级别重复：以下房户存在计费月份重叠的记录\n\n`
    
    if (result.duplicateRecords) {
      result.duplicateRecords.forEach((record, index) => {
        message += `${index + 1}. ${record.householdAddress || `房户ID: ${record.householdId}`}\n`
        message += `   计费周期：${record.billingPeriod}\n`
        message += `   费用金额：${record.amount} 元\n`
        message += `   创建时间：${record.createTime}\n\n`
      })
    }
    
    if (result.overlappingMonths && result.overlappingMonths.length > 0) {
      message += `重叠月份：${result.overlappingMonths.join('、')}\n\n`
    }
  }
  
  message += '请检查并处理重复记录后再进行费用生成。'
  
  await ElMessageBox.alert(message, '重复检查结果', {
    confirmButtonText: '确定',
    type: 'warning',
    dangerouslyUseHTMLString: false
  })
}

/**
 * 费用生成前的重复检查
 * @param params 检查参数
 * @returns Promise<boolean> true-可以生成，false-不能生成
 */
export const checkBeforeGenerate = async (params: {
  communityId: number
  billingPeriod: string
  feeType: number
  feeTypeName: string
}): Promise<boolean> => {
  const { communityId, billingPeriod, feeType, feeTypeName } = params
  
  try {
    let hasDuplicate = false
    
    if (feeType === 1) {
      // 物业费
      hasDuplicate = !(await checkPropertyFeeDuplicate(communityId, billingPeriod, feeType))
    } else if (feeType === 5) {
      // 卫生费
      hasDuplicate = !(await checkSanitationFeeDuplicate(communityId, billingPeriod))
    }
    
    if (hasDuplicate) {
      ElMessage.warning(`${feeTypeName}重复检查未通过，请处理重复记录后再生成`)
      return false
    }
    
    ElMessage.success(`${feeTypeName}重复检查通过，可以生成费用`)
    return true
    
  } catch (error) {
    console.error('费用生成前重复检查失败:', error)
    ElMessage.error('重复检查失败，请重试')
    return false
  }
}

/**
 * 验证计费周期格式
 * @param billingPeriod 计费周期
 * @returns boolean true-格式正确，false-格式错误
 */
export const validateBillingPeriod = (billingPeriod: string): boolean => {
  if (!billingPeriod) {
    ElMessage.error('计费周期不能为空')
    return false
  }
  
  // 检查单月格式：yyyy-MM
  const singleMonthPattern = /^\d{4}-\d{2}$/
  
  // 检查时间段格式：yyyy-MM ~ yyyy-MM
  const rangePattern = /^\d{4}-\d{2}\s*~\s*\d{4}-\d{2}$/
  
  if (!singleMonthPattern.test(billingPeriod) && !rangePattern.test(billingPeriod)) {
    ElMessage.error('计费周期格式错误，应为 "yyyy-MM" 或 "yyyy-MM ~ yyyy-MM" 格式')
    return false
  }
  
  // 检查时间段的有效性
  if (rangePattern.test(billingPeriod)) {
    const parts = billingPeriod.split('~').map(part => part.trim())
    const startMonth = parts[0]
    const endMonth = parts[1]
    
    if (startMonth >= endMonth) {
      ElMessage.error('计费周期开始月份不能晚于或等于结束月份')
      return false
    }
  }
  
  return true
}
